﻿# -------------------- #
# Office Configuration #
# -------------------- #
param([string]$virtualMachineService, [string]$virtualMachineName)

Write-Information "Virtual machine '$virtualMachineName' executing Office '$($script.type)' configuration ... " -NoNewLine $true
$userName = $subscription.virtualMachines.adminUserName
$password = $subscription.virtualMachines.password
$netBiosDomain = $subscription.virtualMachines.netBiosDomain
$uri = Get-AzureWinRMUri -ServiceName $virtualMachineService -Name $virtualMachineName
$credential = New-Object System.Management.Automation.PSCredential(($netBiosDomain + "\" + $userName), (ConvertTo-SecureString $password -AsPlainText -Force))
$session = New-PSSession -ComputerName $uri[0].DnsSafeHost -Credential $credential -Port (Get-VirtualMachineInstanceEndpointPort $subscription $virtualMachineName) -UseSSL
switch ($script.type)
{
	"Install"
	{
		Send-RemoteFile -Source "$env:dp0\Files\$($script.configuration)" -Destination "C:\Office.xml" -Session $session
		Invoke-Command -Session $session -ScriptBlock {
            $result = Start-Process -FilePath "O:\Setup.exe" -ArgumentList "/config C:\Office.xml" -PassThru -Wait
            if ($result.ExitCode -ne 0)
            {
                throw "Office installation failed. Check '$Env:TEMP\Office\Office Professional Plus 2013 Setup *.log' for more details."
            }
			Remove-Item "C:\Office.xml" -Force
		}
	}
	default
	{
		throw "Office type '$($script.type)' is not supported."
	}
}
Remove-PSSession $session
Write-Text "done."